//
//  AddressLevelCtr.swift
//  glive
//
//  Created by zhuxietong on 2020/8/13.
//  Copyright © 2020 zhu xietong. All rights reserved.
//

import Foundation
import XLPagerTabStrip
import Eelay

private let selectedColor:UIColor = UIColor._tint
private let normalColor = UIColor.color(light: "#efefef", dark: "#aaaaaa22")
private let normalTextColor = UIColor.color(light: "#666", dark: "#aaa")



extension AddressLevelCtr:IndicatorInfoProvider{
    
    open func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
        return IndicatorInfo(title: item_["@Name","请选择"].loc)
    }
    
}
open class AddressLevelCtr:ListController{
    
    public var confirm:(_:NSMutableDictionary,_:AddressLevelCtr) ->Void = {_,_ in}

    
    public var recs:NSMutableArray = NSMutableArray(){
        didSet{
            tableView.load(sections: sections, selector: selector)
            tableView.model  <-- ("section1",list,.arrayRefresh)
            tableView.reloadData()
            tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
        }
    }
    
    var sections:TP.section{
        get{
            var sec:TP.section = [
                [
                    ["cellID":"top"],
                ],
                [],
            ]
            if recs.count > 0{
                sec = [
                    [
                        ["cellID":"top"],
                        ["cellID":"rec","options":self.recs],
                    ],
                ]
            }
            
            return sec
        }
    }
    
    
    let selector:TP.selector = [
        "<default>":Cell.self,
        "cellID<top>":BlankLine<line.px1>.self,
        "cellID<rec>":RecCell.self

    ]
    
    public var simpleInfo:NSMutableDictionary{
        get{
            return ["name":item_["@Name",""],"code":item_["@Code",""]].mutable_dictionary
        }
    }
    
    
    var list:NSMutableArray = NSMutableArray(){
        didSet{
            if(list.count > 0){
                isValid = true
            }else{
                isValid = false
            }
            let item = NSMutableDictionary()
            selectItem(item: item)
            if (isDidLoad){
                tableView.model  <-- ("section1",list,.arrayRefresh)
                tableView.reloadData()
                tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
            }
        }
    }
    
    
    var isDidLoad = false
    
    var level = 0
    
    var changeItem:(_:AddressLevelCtr,_:NSMutableDictionary)->Void = {_,_  in}
    
    
    func selectItem(item:NSMutableDictionary) {
        self.item_ = item
    
        if(item.allKeys.count > 1){
            changeItem(self,item)
        }
        tableView.reloadData()
        if (item.allKeys.count > 0){
            if let next = nextCtr{
                if(!next.isValid){
                    confirm(item,self)
                }
            }else{
                confirm(item,self)
            }
        }
        
    }
    
    func updateNextList(item:NSMutableDictionary) {
        if let list = item.object(forKey: "State") as? NSMutableArray{
            nextCtr?.list = list
        }
        else if let _ = item.object(forKey: "State") as? NSMutableDictionary{
            nextCtr?.list = item.get(node: "State.City", defaultV: NSMutableArray())
        }
        else if let list = item.object(forKey: "City") as? NSMutableArray{
            nextCtr?.list = list
        }
        else if let dict = item.object(forKey: "City") as? NSMutableDictionary{
            nextCtr?.list = [dict].mutable_array
        }
        else if let list = item.object(forKey: "Region") as? NSMutableArray{
            nextCtr?.list = list
        }
        else if let dict = item.object(forKey: "Region") as? NSMutableDictionary{
            nextCtr?.list = [dict].mutable_array
        }
        else{
            nextCtr?.list = NSMutableArray()
        }
    }
    
    var item_:NSMutableDictionary = NSMutableDictionary(){
        didSet{
            updateNextList(item: item_)
        }
    }
    
    
    weak var nextCtr:AddressLevelCtr? = nil
    public var isValid = false
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        tableView.backgroundColor = ._background
        tableView.load(sections: sections, selector: selector)
        tableView.model  <-- ("section1",list,.arrayRefresh)
        tableView.separatorInset = .init(top: 0, left: 10, bottom: 0, right: 10)
        tableView.separatorColor = .color(light: "#f0f0f0", dark: "#c0c0c011")
        tableView.reloadData()
        isDidLoad = true

    }
    open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if(indexPath.section == 1){
            if let model = tableView.cellData(at: indexPath){
                selectItem(item: model)
            }
        }
    }
    
    class RecCell: JoTableCell {
        
        public class TextKit: FOptionV {
            public override func setOptionLayout() {
                self.edeg = UIEdgeInsets(top: 5, left: 16, bottom: 5, right: 16)
                eelay = [
                    [imgV,[ee.T.L.B.R]],
                    [titleL,[ee.T.L.B.R,[edeg.top,edeg.left,-edeg.bottom,-edeg.right]],"22"],
                    [bt,[ee.T.L.B.R]],
                ]
                titleL.setContentConstrainToLowLever()
                bt.setContentConstrainToLowLever()
                imgV.setImage(nil, for: .normal)
                imgV.setImage(nil, for: .selected)
                
                self.bsui.set(radius: (1), width: nil, color: nil)
                _ = titleL.ui.center.font13.cl_666
            }
            
            public override func tag_touched() {
                (mo.controller as? AddressLevelCtr)?.selectItem(item: mo.model)
            }
            
            open override var intrinsicContentSize: CGSize
            {
                var s_w = self.edeg.right + self.titleL.intrinsicContentSize.width + self.edeg.left
                let s_h = self.edeg.top + self.edeg.bottom + self.titleL.intrinsicContentSize.height
                if s_w > (Swidth-2*AppTheme.edge)
                {
                    s_w = Swidth-2*AppTheme.edge
                }
                return [s_w, s_h]
            }
            
            public override func mo_model_reload() {
                let name = mo.model.possible("@Name","name", default: " ")
                
                self.titleL.text = name
                
                var is_select = false
                if let selected = (mo.controller as? AddressLevelCtr)?.item_{
                    let s_name = selected.possible("@Name","name", default: "")
                    if(s_name == name){
                        is_select = true
                    }
                }
                if is_select
                {
                    imgV.bsui.background(color: selectedColor)
                    imgV.isSelected =  true
                    _ = titleL.ui.font13.cl_fff
                    self.bsui.background(color: selectedColor)
                    self.bsui.set(radius: 12, width: 1, color: selectedColor)
                }
                else
                {
                    imgV.isSelected = false
                    imgV.bsui.background(color: normalColor)
                    _ = titleL.ui.font13.text(color: .color(light: "#333", dark: "#aaa"))
                    self.bsui.set(radius: 12, width: 1, color: normalColor)
                }
                backgroundColor = .clear
                bt.setImage(nil, for: .normal)
                bt.setImage(nil, for: .selected)
            }
        }
        
        var field = TagsOptionField<TextKit>()
        let titleL = UILabel()
        
        override func addLayoutRules() {
            titleL.ui.bfont14.text(color: ._foregroundWeak)
         
            titleL.setContentConstrainToHighLever()
            contentView.eelay = [
                [titleL,[ee.T.L,[16,16.co]]],
                [field,[ee.L.B.R,0.+1000],[titleL,ee.B,ee.T,4]],
            ]
            
            
            field.tagsV.preferredMaxLayoutWidth = Swidth
            field.tagsV.padding = [10,20.co,18,20.co]
            field.insets = 12
            field.lineSpace = 12
            contentView.backgroundColor = .clear
            self.backgroundColor = .clear
        }
        
        
        override func mo_model_reload() {
            titleL.text = "热门地区".loc
//            field.controller = self.content_controller
            field.mo.model = mo.model
        }
        
    }

    
    
    
    
    
    class Cell: JoTableCell {
        
        let nameL = UILabel()
        let markV = UIImageView()
        override func addLayoutRules() {
            contentView.eelay = [
                [nameL,[ee.T.L.B,[12,20.co,-12]]],
                [markV,[ee.R,.<(-12)],[nameL,ee.Y],[nameL,ee.R,ee.L,8],16,"16"],
            ]
            contentView.backgroundColor = ._background

            nameL.ui.font14.text(color: ._foreground)
            markV.image = UIImage(named: "select-mark-border")?.dynamicImage(color: ._tint)
        }
        
        
        override func mo_model_reload() {
            nameL.text = mo.model.possible("@Name", default: "")
//            nameL.ui.font14.text(color: ._foreground)

            markV.alpha = 0
            if let ctr = mo.controller as? AddressLevelCtr{
                if ctr.item_["@Name",""] == mo.model.possible("@Name", default: "")
                {
                    markV.alpha  = 1
//                    nameL.ui.font14.text(color: ___shop.tint)
                }
            }
//            nameL.attributedText = mo.model.possible("@Name", default: "XX").ui.font14.color(color: ._foreground).astring
        }
//        override func specGetter() -> _Spec {
//            return .inset([], [10], child: nameL.Spec)
//        }
        
        
    }
    
}

public class AddressTabCtr:ButtonBarPagerTabStripViewController{

//    public var address:[String] = ["中国","北京","东城"]{

    public var address:[String] = []{
        didSet{
              updateSelctedIndex()
        }
    }
    
    
    func checkSelect(ctr:AddressLevelCtr,address:[String]) {
        
        weak var ws = self
        var ads = address
        for i0 in Each<NSMutableDictionary>(ctr.list) {
            if(ads.count > 0){
                let n = ads[0]
                if i0["@Name",""] == n{
                    ctr.item_ = i0
                    
                    if let next = ctr.nextCtr{
                        ads.remove(at: 0)
                        if next.isValid{
                            checkSelect(ctr: next, address: ads)
                        }else{
                            reloadCtrs()
                            co_delay(delay: 0.05, closure: {
                                ws?.moveTo(viewController: ctr, animated: false)
                                co_delay(delay: 0.05) {
                                    ws?.buttonBarView.reloadData()
                                }
                            })
                        }
                    }else{
                        reloadCtrs()
                        co_delay(delay: 0.05, closure: {
                            ws?.moveTo(viewController: ctr, animated: false)
                            co_delay(delay: 0.05) {
                                ws?.buttonBarView.reloadData()
                            }
                        })
                    }
                    return
                }
            }else{
                return
            }
        }
    }
  
    
    func updateSelctedIndex() {
        checkSelect(ctr: ctr0, address: address)
    }
    
    public var confirm:(_:NSMutableDictionary,_:NSMutableArray)->Void = {_,_ in}

    
    public func getJson(resource:String) -> NSMutableArray {
        if let path = Bundle.main.path(forResource: resource, ofType: "json") {
            do {
                let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
                let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
                if let list = jsonResult as? Array<Any>
                {
                    return list.mutable_array
                }
                else{
                    return NSMutableArray()
                }
            } catch {
            // maybe lets throw error here
                return NSMutableArray()
            }
        }
        return NSMutableArray()
    }
 
    
    var isReload = false
    
    let ctr0 = AddressLevelCtr()
    let ctr1 = AddressLevelCtr()
    let ctr2 = AddressLevelCtr()
    let ctr3 = AddressLevelCtr()
    
    var countrys = NSMutableArray(){
        didSet{
            updateSelctedIndex()
        }
    }
    
    public override func viewDidLoad() {
        ctr0.level = 0
        ctr1.level = 1
        ctr2.level = 2
        ctr3.level = 3
        ctr0.nextCtr = ctr1
        ctr1.nextCtr = ctr2
        ctr2.nextCtr = ctr3
        
        let ctrs = [ctr0,ctr1,ctr2,ctr3]
        for c in ctrs {
            c.changeItem = {[weak self]
                ctr,item in
                
                self?.reloadCtrs()

                if let next = ctr.nextCtr{
                    if (next.isValid){
                        self?.moveTo(viewController: next, animated: true)
                    }
                }
//                self?.currentIndex = ctr.level  + 1
            }
            c.confirm = {[weak self]
                item,ctr in
                
                let list = NSMutableArray()
                if let ws = self{
                    list.add(ws.ctr0.simpleInfo)
                    if ws.ctr1.isValid{
                        list.add(ws.ctr1.simpleInfo)
                    }
                    if ws.ctr2.isValid{
                        list.add(ws.ctr2.simpleInfo)
                    }
                    if ws.ctr3.isValid{
                        list.add(ws.ctr3.simpleInfo)
                    }
                }
            
                self?.confirm(item,list)
                
            }
        }
        

        
        
//        print(")))S)S--",countrys)
        
        
//        loadChilds()
        view.backgroundColor = ._background
        changeCurrentIndexProgressive = { (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in
            guard changeCurrentIndex == true else { return }
            oldCell?.label.textColor = .color(light: "#444", dark: "#fff9")
            newCell?.label.textColor = ._tint
            if animated {
                UIView.animate(withDuration: 0.1, animations: { () -> Void in
                    newCell?.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
                    oldCell?.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
                })
            } else {
                newCell?.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
                oldCell?.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
            }
        }
        
        settings.style.buttonBarBackgroundColor = ._background
        settings.style.buttonBarItemBackgroundColor = ._background
        //               settings.style.selectedBarBackgroundColor = UIColor(red: 33/255.0, green: 174/255.0, blue: 67/255.0, alpha: 1.0)
        settings.style.buttonBarItemFont = .systemFont(ofSize: 14)
        settings.style.selectedBarHeight = 2.0
        settings.style.buttonBarHeight = 36
        settings.style.buttonBarMinimumLineSpacing = 0
        settings.style.buttonBarItemTitleColor = ._foreground
        //        settings.style.buttonBarItemsShouldFillAvailableWidth = true
        settings.style.buttonBarLeftContentInset = 12.co
        settings.style.buttonBarRightContentInset = 12.co
        settings.style.buttonBarItemLeftRightMargin = 6
        settings.style.selectedBarBackgroundColor = .clear
        settings.style.buttonBarItemsShouldFillAvailableWidth = false
        //        settings.style.selectedBarBackgroundColor = .color(light: "#FF5F5F", dark: "#FF5F5F")
        
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        let buttonBarHeight = settings.style.buttonBarHeight ?? 44
        let buttonBar = AddressButtonBarView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: buttonBarHeight), collectionViewLayout: flowLayout)
       
        
//        buttonBar.selectedBar.backgroundColor = .black
//        buttonBar.autoresizingMask = [.flexibleWidth,.flexibleTopMargin,.flexibleRightMargin]
        
        
        self.buttonBarView = buttonBar
//        containerView.frame = newContainerViewFrame
        
        super.viewDidLoad()
        
        view.eelay = [
            [buttonBar,[ee.T.L.R],"\(buttonBarHeight)"],
            [containerView!,[buttonBar,ee.B,ee.T],[ee.L.R.B]]
        ]
        __notice.add(task: (TP.Notice.localizableDidChange,{[weak self] n in
            self?.reloadCtrs()
        }))
        
        var countrys = NSMutableArray()
        
        if let path = Bundle(for: AddressSelector.self).path(forResource: "soappAddress", ofType: "bundle"){
            if let bundle = Bundle(path: path){
                
                let xmlName = "LocList_\(MoLocalizable.lproj)"
                print("+____|\(xmlName)__")
                if let p = bundle.path(forResource: xmlName, ofType: "xml"){
                    print("-------ssss|----")
                    let url_ = URL(fileURLWithPath: p)
                    xmlReader.parse(url: url_) { (json) in
                        let obj = json?.mutable_dictionary ?? NSMutableDictionary()
                        countrys = obj.get(node: "Location.CountryRegion", defaultV: NSMutableArray())
                    }
                }else{
                    if let p = bundle.path(forResource: "LocList_en", ofType: "xml"){
                        let url_ = URL(fileURLWithPath: p)
                        xmlReader.parse(url: url_) { (json) in
                            let obj = json?.mutable_dictionary ?? NSMutableDictionary()
                            countrys = obj.get(node: "Location.CountryRegion", defaultV: NSMutableArray())
                        }
                    }
                }
            }
            else{
            }
        }else{
        }
        
        
//        if let path = Bundle(for: AddressTabCtr.self).path(forResource: "LocList_zh", ofType: "xml")
//        {
//
//
//            let url_ = URL(fileURLWithPath: path)
//            xmlReader.parse(url: url_) { (json) in
//            let obj = json?.mutable_dictionary ?? NSMutableDictionary()
//                countrys = obj.get(node: "Location.CountryRegion", defaultV: NSMutableArray())
//            }
//        }
        
        
//        let countrys = getJson(resource: "countrys_zh")
        
        let rec_country_names = ["中国".loc,"韩国".loc,"日本".loc,"泰国".loc,"越南".loc]
        
        let recs = NSMutableArray()
        
        for c in Each<NSMutableDictionary>(countrys){
            let name = c["@Name",""]
            if(rec_country_names.contains(name)){
                recs.add(c)
            }
        }
     
        
        ctr0.recs = recs
        ctr0.list = countrys
        self.countrys = countrys
        
        
              
    }
    
    var xmlReader = XMLReader()
    @objc func reloadCtrs() {
        reloadPagerTabStripView()
    }
    
    public override func reloadPagerTabStripView() {
//        isReload = true
//        if arc4random() % 2 == 0 {
//            pagerBehaviour = .progressive(skipIntermediateViewControllers: arc4random() % 2 == 0, elasticIndicatorLimit: arc4random() % 2 == 0 )
//        } else {
//            pagerBehaviour = .common(skipIntermediateViewControllers: arc4random() % 2 == 0)
//        }
        super.reloadPagerTabStripView()
    }
    var childs:[AddressLevelCtr]
    {
        get{
            
            var list:[AddressLevelCtr] = [ctr0]
            if (ctr1.isValid){list.append(ctr1)}
            if (ctr2.isValid){list.append(ctr2)}
            if (ctr3.isValid){list.append(ctr3)}
            return list
        }
    }
    
    let sep_line = UIView()
    
    
    open func loadChilds (){
        reloadPagerTabStripView()
    }
    
    // MARK: - PagerTabStripDataSource
    open override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
        
        return self.childs
    }
}




class AddressButtonBarView:ButtonBarView{
    let indicatorV = UIView()
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        selectedBar.eelay = [
            [indicatorV,[ee.X.T.B],12]
        ]
        indicatorV.bsui.set(radius: 1, width: nil, color: nil)
        indicatorV.backgroundColor = ._tint
        //       addSubview(selectedBar)
    }
    
    public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        selectedBar.eelay = [
            [indicatorV,[ee.X.T.B],12]
        ]
        indicatorV.backgroundColor = ._tint
        
        //       addSubview(selectedBar)
    }
}
